package com.example.blank700.musicplayer;

import android.database.Cursor;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.blank700.data.Music;
import com.example.blank700.data.MusicList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    //显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;

    private ArrayList<Music> musicArrayList;

    //当前歌曲的序号，下标从0开始
    private int number = 0;

    //用于判断是否要从头播放
    private int isRestart = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findView();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicfile();
    }

    /*获取显示组件*/
    private void findView() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
    }

    /*为显示组件注册监听器*/
    private void registerListeners() {
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moveNumberToPrevious();
                play(number);
                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (player != null && player.isPlaying()) {
                    pause();
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                } else {
                    if (isRestart == 1) {
                        play(number);
                        isRestart = 0;//表示不需要从头播放
                    } else {
                        player.start();
                    }
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stop();
                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                isRestart = 1;//表示要从头播放
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moveNumberToNext();
                play(number);
                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (number == position) {//判断是否点击了当前正在播放的音乐
                    if (player != null && player.isPlaying()){

                    }
                } else {
                    number = position;
                    play(number);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                    isRestart = 0;//表示不需要从头播放
                }
            }
        });
    }

    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    }, null, null, MediaStore.Audio.AudioColumns.TITLE);

            if (mMusicCursor != null) {
                //标题
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                //艺术家
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                //路径
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                //总时长
                int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);

                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String strTitle = mMusicCursor.getString(indexTitle);
                    String strArtist = mMusicCursor.getString(indexArtist);
                    String strPath = mMusicCursor.getString(indexPath);
                    String strTotalTime = mMusicCursor.getString(indexTotalTime);
                    if (strArtist.equals("<unknown>"))
                        strArtist = "无艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strTotalTime);
                    musicArrayList.add(music);
                }
            }
        }
    }

    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_tv_title_item, R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }

    private void checkMusicfile() {
        if (musicArrayList.isEmpty()) {
            imgBtn_Previous.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            imgBtn_Next.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Previous.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
            imgBtn_Next.setEnabled(true);
        }
    }

    //媒体播放类
    private MediaPlayer player = new MediaPlayer();

    //读取音乐文件
    private void load(int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getMusicPath());
            player.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //播放音乐
    private void play(int number) {
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        player.start();
    }

    //暂停音乐
    private void pause() {
        if (player.isPlaying()) {
            player.pause();
        }
    }

    //停止播放
    private void stop() {
        player.stop();
    }

    //恢复播放（暂停之后）
    private void resume() {
        player.start();
    }

    //重新播放（播放完成之后）
    private void replay() {
        player.start();
    }

    private void moveNumberToNext() {
        //判断是否有到达列表底端
        if ((number) == MusicList.getMusicList().size() - 1) {
            Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.tip_reach_bottom),
                    Toast.LENGTH_SHORT).show();
        } else {
            ++number;
            play(number);
        }
    }

    private void moveNumberToPrevious() {
        //判断是否有到达列表顶端
        if (number == 0) {
            Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.tip_reach_top),
                    Toast.LENGTH_SHORT).show();
        } else {
            --number;
            play(number);
        }
    }
}
